
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin') // 引入HtmlWebpackPlugin插件
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader/dist/index');
const tsImportPluginFactory = require('ts-import-plugin');
const autoprefixer = require('autoprefixer');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const notifier = require('node-notifier');
const icon = path.join(__dirname, 'public/icon.jpg');

//定义好入口文件和出口文件
module.exports = {
    entry: {
        index: path.join(__dirname, '../src/index.ts'),
    },
    output: {
        path: path.resolve(__dirname, './dist'), //打包后的文件存放的地方
        filename: 'js/[name].[hash].js', // 每次保存 hash 都变化
    },
    module: {
        rules: [

            // {
            //     test: /\.js$/,
            //     use: {
            //         loader: 'babel-loader',
            //         options: {
            //             presets: ['@babel/preset-env']
            //         }
            //     }
            // },
            {
                test: /\.vue$/,
                use: [
                    'vue-loader'
                ],

            },
            {
                test: /\.css$/,
                use: [
                    // MiniCssExtractPlugin.loader,
                    'cache-loader',
                    'style-loader',
                    'css-loader',
                    /**
                     * css兼容处理
                     */
                    //  {
                    //     loader: 'postcss-loader',
                    //     options: {
                    //       postcssOptions: {
                    //         plugins: [
                    //           [
                    //             'postcss-preset-env',
                    //             {
                    //               // 其他选项
                    //             },
                    //           ],
                    //           autoprefixer(),
                    //         ],
                    //       },
                    //     },
                    //   },
                ]
            },
            {
                test: /\.less$/,
                use: [
                    // MiniCssExtractPlugin.loader,
                    // 'style-loader',
                    'css-loader',
                    'less-loader'
                ]
            },
            {
                test: /\.(jpg|png|jpeg|gif|bmp)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 1024,
                            fallback: {
                                loader: 'file-loader',
                                options: {
                                    name: '[name].[ext]'
                                }
                            }
                        },
                    },
                    // {
                    //     loader: 'image-webpack-loader',
                    //     options: {
                    //         mozjpeg: {
                    //             progressive: true,
                    //         },
                    //         optipng: {
                    //             enabled: false,
                    //         },
                    //         pngquant: {
                    //             quality: [0.65, 0.90],
                    //             speed: 4
                    //         },
                    //         gifsicle: {
                    //             interlaced: false,
                    //         },
                    //         webp: {
                    //             quality: 75
                    //         }
                    //     }
                    // }


                ]
            },
            {
                test: /\.(mp4|ogg|mp3|wav)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 1024,
                        fallback: {
                            loader: 'file-loader',
                            options: {
                                name: '[name].[ext]'
                            }
                        }
                    }
                }
            },
            {
                test: /\.ts$/,
                use: [
                    {
                        loader: 'ts-loader',
                        options: {
                            transpileOnly: true,
                            getCustomTransformers: () => ({
                                before: [
                                    tsImportPluginFactory({
                                        libraryName: 'vant',
                                        libraryDirectory: 'es',
                                        style: (name) => `${name}/style/less`,
                                    }),
                                ],
                            }),
                            compilerOptions: {
                                module: 'es2015',
                            },
                        }
                    },
                ],
                exclude: /node_modules/
            },
            {
                test: /\.(t|j)s$/,
                exclude: /node_modules/,
                include: [path.resolve(__dirname, './src')],
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                            cacheDirectory: true
                        }
                        // presets: ['@babel/preset-env'],

                    },
                ],
            },
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx', '.json', '.ts'],	//表示在import 文件时文件后缀名可以不写
        alias: {
            '@': path.join(__dirname, './src')
            //表示设置路径别名这样在import的文件在src下的时候可以直接 @/component/...
        }
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, '../src/index.html'), // new一个这个插件的实例，并传入相关的参数
            // bug2:index.html路径问题导致( 模板路径是相对于项目最外层的package.json）
            filename: 'index.html',
            minify: {
                collapseWhitespace: true, // 去掉空格
                removeComments: true // 去掉注释
            },
            title: 'Vue3 + TS -> Web App'//配置动态网页标题时，需将模板中的 <title> 标签里的内容改成 <%= htmlWebpackPlugin.options.title %>
        }),
        new VueLoaderPlugin(),
        // new OptimizeCssAssetsWebpackPlugin(),// 不支持webpack5
        // new MiniCssExtractPlugin({
        //     filename: 'css/[name].css'
        // }),// 报错所以注释掉
        new CleanWebpackPlugin(),
        new FriendlyErrorsWebpackPlugin({
            onErrors: (severity, errors) => {
                notifier.notify({
                    title: 'webpack 编译失败了~',
                    message: `${severity} ${errors[0].name}`,
                    subtitle: errors[0].file || '',
                    icon,
                });
            },
        }),

    ],
    // configureWebpack: {
    //     // provide the app's title in webpack's name field, so that
    //     // it can be accessed in index.html to inject the correct title.
    //     resolve: {
    //         fallback: { path: require.resolve("path-browserify") },
    //     },
    // },
    optimization: {
        minimize: true,
        minimizer: [
            new TerserWebpackPlugin()
        ]
    },
    target: process.env.NODE_ENV === 'development' ? 'web' : 'browserslist',
}